import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/posts.dart';
import '../models/comment.dart';
import '../services/token_manager.dart';
import '../servers/api_service.dart';

class PostsService {
  // 修改为你的后端服务器地址
  static const String baseUrl = 'http://192.168.101.13:8080';
  // 如果在真机上运行，使用：static const String baseUrl = 'http://192.168.1.xxx:8080';
  
  // 缓存当前用户的 userId，避免频繁请求服务器
  int? _cachedUserId;
  
  /// 从后端API获取用户ID（通过email查询）
  Future<int?> _getUserIdFromBackend(String email) async {
    try {
      print('📡 调用后端API获取userId: $email');
      final response = await http.get(
        Uri.parse('$baseUrl/auth/userid?email=$email'),
        headers: {
          'Content-Type': 'application/json',
        },
      );
      
      print('📥 后端API响应状态: ${response.statusCode}');
      print('📥 后端API响应内容: ${response.body}');
      
      if (response.statusCode == 200) {
        final result = jsonDecode(response.body);
        
        // 解析 Result 格式：{ code: 1 或 200, msg/message: "...", data: { id: 123 } }
        final code = result['code'];
        final data = result['data'];
        
        // 支持 code == 1（成功）或 code == 200
        final isSuccess = code == 1 || code == 200;
        
        if (isSuccess && data != null) {
          // 从 data.id 中获取用户ID
          final userId = data['id'];
          
          if (userId != null) {
            int id;
            if (userId is int) {
              id = userId;
            } else if (userId is String) {
              id = int.tryParse(userId) ?? 0;
            } else {
              id = int.tryParse(userId.toString()) ?? 0;
            }
            
            if (id > 0) {
              print('✅ 从后端API成功获取 userId: $id');
              return id;
            } else {
              print('❌ 用户ID无效: $userId');
            }
          } else {
            print('❌ 返回数据中没有 id 字段');
            print('   返回的 data: $data');
          }
        } else {
          final message = result['msg'] ?? result['message'] ?? '未知错误';
          print('❌ 后端返回错误: code=$code, message=$message');
        }
      } else {
        print('❌ 后端API返回失败: ${response.statusCode} - ${response.body}');
      }
      
      return null;
    } catch (e, stackTrace) {
      print('❌ 调用后端API获取userId失败: $e');
      print('   堆栈跟踪: $stackTrace');
      return null;
    }
  }
  
  /// 获取当前登录用户的 userId
  Future<int?> _getCurrentUserId() async {
    // 如果缓存中有，直接返回
    if (_cachedUserId != null) {
      print('✅ 使用缓存的 userId: $_cachedUserId');
      return _cachedUserId;
    }
    
    try {
      // 获取用户邮箱
      final userInfo = await TokenManager.instance.getUserInfo();
      final email = userInfo['email'];
      
      print('🔍 获取用户ID | Email: $email');
      
      if (email == null || email.isEmpty) {
        print('❌ 用户邮箱为空，无法获取用户ID');
        return null;
      }
      
      // 方案1：从后端API直接获取userId（推荐，需要后端支持）
      print('📡 尝试从后端API获取userId...');
      final userIdFromApi = await _getUserIdFromBackend(email);
      if (userIdFromApi != null && userIdFromApi > 0) {
        _cachedUserId = userIdFromApi;
        print('✅ 成功从后端API获取并缓存 userId: $userIdFromApi');
        return _cachedUserId;
      }
      
      // 方案2：从服务器获取完整用户信息（包含 id）
      final apiService = ApiService();
      print('📡 尝试从 /auth/userinfo 获取用户信息...');
      final fullUserInfo = await apiService.getUserInfo(email);
      
      print('📥 服务器返回的用户信息: $fullUserInfo');
      
      if (fullUserInfo != null) {
        // 检查 id 字段（可能是 int 或 String）
        final id = fullUserInfo['id'];
        if (id != null) {
          int userId;
          if (id is int) {
            userId = id;
          } else if (id is String) {
            userId = int.tryParse(id) ?? 0;
          } else {
            userId = int.tryParse(id.toString()) ?? 0;
          }
          
          if (userId > 0) {
            _cachedUserId = userId;
            print('✅ 从用户信息成功获取并缓存 userId: $userId');
            return _cachedUserId;
          } else {
            print('❌ 用户ID无效: $id');
          }
        } else {
          print('❌ 服务器返回的用户信息中没有 id 字段');
          print('   可用字段: ${fullUserInfo.keys.toList()}');
        }
      }
      
      // 方案3：从 JWT token 中解析 userId
      try {
        final token = await TokenManager.instance.getToken();
        if (token != null && token.isNotEmpty) {
          print('🔐 尝试从 JWT token 解析 userId...');
          final payload = TokenManager.instance.parseJWT(token);
          
          if (payload != null) {
            print('📦 JWT payload: $payload');
            
            // 尝试不同的字段名：id, userId, sub, user_id
            final idFromToken = payload['id'] ?? 
                                payload['userId'] ?? 
                                payload['sub'] ?? 
                                payload['user_id'];
            
            if (idFromToken != null) {
              int userId;
              if (idFromToken is int) {
                userId = idFromToken;
              } else if (idFromToken is String) {
                userId = int.tryParse(idFromToken) ?? 0;
              } else {
                userId = int.tryParse(idFromToken.toString()) ?? 0;
              }
              
              if (userId > 0) {
                _cachedUserId = userId;
                print('✅ 从 JWT token 成功解析并缓存 userId: $userId');
                return _cachedUserId;
              } else {
                print('❌ JWT token 中的用户ID无效: $idFromToken');
              }
            } else {
              print('❌ JWT token 中没有找到用户ID字段');
              print('   JWT payload 可用字段: ${payload.keys.toList()}');
            }
          }
        }
      } catch (e) {
        print('❌ 从 JWT token 解析用户ID失败: $e');
      }
      
      print('⚠️ 警告：所有方式都无法获取userId，后端可能需要添加根据email查询userId的接口');
      return null;
    } catch (e, stackTrace) {
      print('❌ 获取用户ID失败: $e');
      print('   堆栈跟踪: $stackTrace');
      return null;
    }
  }

  /// 新增帖子（按后端要求：接收 PostsDTO，返回 Result 包装）
  Future<bool> savePost({
    required String title,
    required String content,
    String? userName,
    String? imageUrl,
    List<String>? imageUrls,
  }) async {
    try {
      // 获取用户信息（用户名和头像）
      final userInfo = await TokenManager.instance.getUserInfo();
      final authorName = userName ?? userInfo['username'] ?? '用户';
      final avatarUrl = userInfo['avatar']; // 获取用户头像
      
      final response = await http.post(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'title': title,
          'content': content,
          // PostsDTO 字段：author
          'author': authorName,
          // 传递用户头像
          if (avatarUrl != null && avatarUrl.isNotEmpty) 'avatarUrl': avatarUrl,
          if (imageUrl != null && imageUrl.isNotEmpty) 'imageUrl': imageUrl,
          if (imageUrls != null && imageUrls.isNotEmpty) 'imageUrls': imageUrls.join(','),
        }),
      );

      if (response.statusCode == 200) {
        // 如果后端使用包装结构，尝试读取 code 判断
        try {
          final map = jsonDecode(response.body) as Map<String, dynamic>;
          final code = map['code'];
          if (code is int) return code == 200 || code == 1 || code == 0;
        } catch (_) {}
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  /// 获取所有帖子
  Future<List<Posts>> getAllPosts() async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      // 构建 URL，添加 userId 查询参数
      final uri = userId != null 
          ? Uri.parse('$baseUrl/posts').replace(queryParameters: {'userId': userId.toString()})
          : Uri.parse('$baseUrl/posts');
      
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        // 支持 Result 包装结构：Result.success(list)
        final data = body is Map<String, dynamic> ? body['data'] : body;
        final list = (data as List).map((e) => Posts.fromJson(e as Map<String, dynamic>)).toList();
        return list;
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }

  /// 根据 ID 获取帖子详情
  Future<Posts> getById(int id) async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      // 构建 URL，添加 userId 查询参数
      final uri = userId != null
          ? Uri.parse('$baseUrl/posts/$id').replace(queryParameters: {'userId': userId.toString()})
          : Uri.parse('$baseUrl/posts/$id');
      
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        // 支持 Result 包装结构：Result.success(posts)
        final data = body is Map<String, dynamic> ? (body['data'] ?? body) : body;
        return Posts.fromJson(data as Map<String, dynamic>);
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }

  /// 获取用户发布的帖子
  Future<List<Posts>> getMyPosts() async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      if (userId == null) {
        throw Exception('无法获取用户ID，请先登录');
      }
      
      print('📡 调用获取我的发布接口: userId=$userId');
      
      // 调用后端API获取用户发布的帖子
      final uri = Uri.parse('$baseUrl/posts/my').replace(
        queryParameters: {'userId': userId.toString()},
      );
      
      print('📡 请求URL: $uri');
      
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
      );

      print('📥 响应状态码: ${response.statusCode}');
      print('📥 响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        print('📦 解析后的数据: $body');
        
        // 支持 Result 包装结构：Result.success(list)
        final data = body is Map<String, dynamic> ? body['data'] : body;
        
        if (data == null) {
          print('⚠️ 返回数据为空');
          return [];
        }
        
        if (data is List) {
          final list = data.map((e) {
            try {
              return Posts.fromJson(e as Map<String, dynamic>);
            } catch (e) {
              print('❌ 解析帖子失败: $e, 原始数据: $e');
              return null;
            }
          }).whereType<Posts>().toList();
          
          print('✅ 成功解析 ${list.length} 条我的发布');
          return list;
        } else {
          print('⚠️ 返回数据格式错误，不是数组: ${data.runtimeType}');
          return [];
        }
      } else {
        print('❌ 请求失败: ${response.statusCode} - ${response.body}');
        throw Exception('HTTP ${response.statusCode}: ${response.body}');
      }
    } catch (e, stackTrace) {
      print('❌ 获取我的发布失败: $e');
      print('   堆栈跟踪: $stackTrace');
      rethrow;
    }
  }

  /// 获取用户点赞的帖子
  Future<List<Posts>> getLikedPosts() async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      if (userId == null) {
        throw Exception('无法获取用户ID，请先登录');
      }
      
      print('📡 调用获取我的点赞接口: userId=$userId');
      
      // 调用后端API获取用户点赞的帖子
      final uri = Uri.parse('$baseUrl/posts/liked').replace(
        queryParameters: {'userId': userId.toString()},
      );
      
      print('📡 请求URL: $uri');
      
      final response = await http.get(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
      );

      print('📥 响应状态码: ${response.statusCode}');
      print('📥 响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        print('📦 解析后的数据: $body');
        
        // 支持 Result 包装结构：Result.success(list)
        final data = body is Map<String, dynamic> ? body['data'] : body;
        
        if (data == null) {
          print('⚠️ 返回数据为空');
          return [];
        }
        
        if (data is List) {
          final list = data.map((e) {
            try {
              final postJson = e as Map<String, dynamic>;
              // 确保 isLiked 字段为 true（因为这些都是用户点赞的帖子）
              postJson['isLiked'] = true;
              return Posts.fromJson(postJson);
            } catch (e) {
              print('❌ 解析帖子失败: $e, 原始数据: $e');
              return null;
            }
          }).whereType<Posts>().toList();
          
          print('✅ 成功解析 ${list.length} 条我的点赞');
          return list;
        } else {
          print('⚠️ 返回数据格式错误，不是数组: ${data.runtimeType}');
          return [];
        }
      } else {
        print('❌ 请求失败: ${response.statusCode} - ${response.body}');
        throw Exception('HTTP ${response.statusCode}: ${response.body}');
      }
    } catch (e, stackTrace) {
      print('❌ 获取我的点赞失败: $e');
      print('   堆栈跟踪: $stackTrace');
      rethrow;
    }
  }

  /// 点赞/取消点赞
  Future<bool> toggleLike(int postId) async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      if (userId == null) {
        throw Exception('无法获取用户ID，请先登录');
      }
      
      // 构建 URL，添加 userId 查询参数
      final uri = Uri.parse('$baseUrl/posts/$postId/like').replace(
        queryParameters: {'userId': userId.toString()},
      );
      
      final response = await http.post(
        uri,
        headers: {
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        // 返回最新的点赞状态：Result.success({isLiked: true/false})
        if (body is Map<String, dynamic>) {
          final data = body['data'];
          if (data is Map<String, dynamic>) {
            return data['isLiked'] == true;
          }
        }
        return false;
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }

  /// 获取帖子的评论列表
  Future<List<Comment>> getComments(int postId) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/posts/$postId/comments'),
        headers: {
          'Content-Type': 'application/json',
        },
      );

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        final data = body is Map<String, dynamic> ? body['data'] : body;
        if (data is List) {
          return data.map((e) => Comment.fromJson(e as Map<String, dynamic>)).toList();
        }
        return [];
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }

  /// 添加评论
  Future<Comment?> addComment(int postId, String content) async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      if (userId == null) {
        throw Exception('无法获取用户ID，请先登录');
      }
      
      final userInfo = await TokenManager.instance.getUserInfo();
      final userName = userInfo['username'] ?? '用户';
      final avatarUrl = userInfo['avatar'];

      final contentPreview = content.length > 20 ? '${content.substring(0, 20)}...' : content;
      print('📝 提交评论 | postId=$postId | userId=$userId | userName=$userName | content=$contentPreview');

      final response = await http.post(
        Uri.parse('$baseUrl/posts/$postId/comments'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'postId': postId,
          'content': content,
          'userId': userId,
          'userName': userName,
          if (avatarUrl != null && avatarUrl.isNotEmpty) 'avatarUrl': avatarUrl,
        }),
      );

      print('📥 评论响应状态码: ${response.statusCode}');
      print('📥 评论响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        final data = body is Map<String, dynamic> ? body['data'] : body;
        if (data is Map<String, dynamic>) {
          return Comment.fromJson(data);
        }
        return null;
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      rethrow;
    }
  }

  /// 获取评论数量
  Future<int> getCommentCount(int postId) async {
    try {
      final comments = await getComments(postId);
      return comments.length;
    } catch (e) {
      return 0;
    }
  }

  /// 删除评论
  Future<bool> deleteComment(int postId, int commentId) async {
    try {
      // 获取当前登录用户的 userId
      final userId = await _getCurrentUserId();
      
      if (userId == null) {
        throw Exception('无法获取用户ID，请先登录');
      }

      print('🗑️ 删除评论 | postId=$postId | commentId=$commentId | userId=$userId');

      final response = await http.delete(
        Uri.parse('$baseUrl/posts/$postId/comments/$commentId').replace(
          queryParameters: {'userId': userId.toString()},
        ),
        headers: {
          'Content-Type': 'application/json',
        },
      );

      print('📥 删除评论响应状态码: ${response.statusCode}');
      print('📥 删除评论响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final body = jsonDecode(response.body);
        final code = body is Map<String, dynamic> ? body['code'] : null;
        // 支持 code == 1 或 code == 200 或直接200状态码
        return code == 1 || code == 200 || response.statusCode == 200;
      } else {
        throw Exception('HTTP ${response.statusCode}');
      }
    } catch (e) {
      print('❌ 删除评论失败: $e');
      rethrow;
    }
  }
}


